package com.buaa.rental.Util;

import com.buaa.rental.Dao.User;
import com.buaa.rental.Dao.User.Role;
import com.buaa.rental.Service.UserService;
import com.buaa.rental.Util.MyAnnotations.Authorization;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthorizedInterceptor implements HandlerInterceptor
{

	@Autowired
	private UserService userService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws CodeException
	{
		String originHeader = request.getHeader("Origin");
		if (originHeader != null && (originHeader.equals("http://localhost") || originHeader.equals("http://localhost:1024") || originHeader.equals("http://114.116.171.72")))
		{
			response.addHeader("Access-Control-Allow-Origin", originHeader);
			response.addHeader("Access-Control-Allow-Headers",
					"Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
			response.addHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
			response.addHeader("Access-Control-Allow-Credentials", "true");

		}

		/*if (userService == null)
		{
			System.out.println("nmsl");
			BeanFactory factory = WebApplicationContextUtils
					.getRequiredWebApplicationContext(request.getServletContext());
			userService = (UserService) factory.getBean("userService");
		}*/
		if (!(o instanceof HandlerMethod))
		{
			return true;
		}
		HandlerMethod handlerMethod = ((HandlerMethod) o);

		Method method = handlerMethod.getMethod();
		//获取方法上的Authorization注解
		Authorization tokenValid = method.getAnnotation(Authorization.class);
		//如果方法上有Authorization注解
		if (tokenValid == null)
		{
			return true;
		}
		Cookie[] cookies = request.getCookies();
		if (cookies == null)
		{
			throw new CodeException("110", "login");
		}
		HttpSession session = request.getSession();
		if (session == null)
		{
			throw new CodeException("110", "login");
		}

		String sessionId = session.getId();
		//System.out.println(sessionId);
		for (Cookie cookie : cookies)
		{
			if (cookie.getName().equals("JSESSIONID"))
			{
				if (!cookie.getValue().equals(sessionId))
				{
					throw new CodeException("110", "login");
				}
				break;
			}
		}

		for (Cookie cookie2 : cookies)
		{
			if (cookie2.getName().equals("uid") && cookie2.getValue() != null)
			{
				try
				{
					User user = userService
							.getUserById(cookie2.getValue());
					String email = (String) session.getAttribute("email");
					String psw = (String) session.getAttribute("psw");
					if (user.email.equals(email) && user.psw.equals(psw))
					{
						if (tokenValid.role() != Role.none && user.role != tokenValid.role())
						{
							throw new CodeException("111", "没有权限");
						}
						request.setAttribute("user", user);
						return true;
					} else
					{
						throw new CodeException("110", "login");
					}
				} catch (NullPointerException e)
				{
					throw new CodeException("110", "login");
				}
			}
		}
		throw new CodeException("110", "login");
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object o, ModelAndView modelAndView)
			throws Exception
	{

	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object o, Exception e) throws Exception
	{

	}
}
